<template>
  <div>
    <!-- 图片上传按钮 -->
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :http-request="customRequest"
      :on-success="handleSuccess"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>

    <!-- 已上传的图片展示 -->
    <div v-if="value" class="uploaded-image">
      <img :src="value" alt="Uploaded Image" class="avatar">
      <el-button size="small" type="danger" @click="clearImage">清除图片</el-button>
    </div>
  </div>
</template>

<script>
import { uploadFile } from '@/api/system' // 替换为你的上传逻辑

export default {
  name: 'ImageUpload',
  props: {
    value: { type: String, default: '' } // 绑定图片 URL
  },
  methods: {
    // 自定义上传逻辑
    customRequest({ file, onSuccess, onError }) {
      const loading = this.$loading({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      uploadFile(file)
        .then((url) => {
          // 上传成功
          onSuccess(url)
        })
        .catch((error) => {
          // 上传失败
          onError(error)
        })
        .finally(() => {
          loading.close()
        })
    },

    // 上传成功处理
    handleSuccess(response) {
      this.$message.success('图片上传成功!')
      this.$emit('input', response.data[0].url) // 更新父组件的绑定值
    },

    // 上传失败处理
    // handleError(error) {
    //   // this.$message.error("图片上传失败: " + error.message);
    // },
    // 清除图片
    clearImage() {
      this.$emit('input', '') // 清空绑定值
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  margin-bottom: 10px;
}

.uploaded-image {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  margin-right: 10px;
  object-fit: cover;
  border: 1px solid #dcdcdc;
}
</style>
